package com.cn.ylg.intentservicedemo;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import static com.cn.ylg.intentservicedemo.MainActivity.UPLOAD_RESULT;

/**
 * Created by Administrator on 2017/3/23.
 */

public class UploadImgService extends IntentService {

    private static final String ACTION_UPLOAD_IMG = "com.zhy.blogcodes.intentservice.action.UPLOAD_IMAGE";
    public static final String EXTRA_IMG_PATH = "com.zhy.blogcodes.intentservice.extra.IMG_PATH";

    /**
     * 服务的入口
     * @param context
     * @param path
     */
    public static void startUploadImg(Context context, String path)
    {
        Intent intent = new Intent(context, UploadImgService.class);
        intent.setAction(ACTION_UPLOAD_IMG);
        intent.putExtra(EXTRA_IMG_PATH, path);
        context.startService(intent);
    }

    public UploadImgService(){
        super("UpLoadImgService");
    }


    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.e("==================","onCreate");
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.e("==================","onDestroy");
    }



    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent!=null){
            //获得action
            final String action = intent.getAction();
            if (ACTION_UPLOAD_IMG.equals(action))
            {
                final String path = intent.getStringExtra(EXTRA_IMG_PATH);
                handleUploadImg(path);
            }
        }
    }
    private void handleUploadImg(String path)
    {
        try
        {
            //模拟上传耗时
            Thread.sleep(3000);

            Intent intent = new Intent(UPLOAD_RESULT);
            intent.putExtra(EXTRA_IMG_PATH, path);
            sendBroadcast(intent);//发送广播

        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}
